<template>
  <div class="transaction-container">
    <h2>客户缴费管理</h2>

    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        <el-form-item label="房屋编号">
          <el-input v-model="searchForm.houseId" placeholder="请输入房屋编号"></el-input>
        </el-form-item>
        <el-form-item label="交易状态">
          <el-select v-model="searchForm.status" placeholder="请选择交易状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="已交" value="已交"></el-option>
            <el-option label="未交" value="未交"></el-option>
            <el-option label="部分支付" value="部分支付"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 交易统计 -->
    <div class="stats-container">
      <h3>缴费情况</h3>
      <div class="stats-cards">
        <el-card class="stat-card">
          <div class="stat-title">总交易数</div>
          <div class="stat-value">{{ stats.totalTransactions }}</div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-title">已交比例</div>
          <div class="stat-value">{{ stats.paidRate }}%</div>
          <el-progress
              :percentage="stats.paidRate"
              :color="getRateColor(stats.paidRate)"
              :show-text="false">
          </el-progress>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-title">需收金额</div>
          <div class="stat-value">¥{{ stats.totalAmount.toLocaleString() }}</div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-title">已收金额</div>
          <div class="stat-value">¥{{ stats.paidAmount.toLocaleString() }}</div>
        </el-card>
      </div>
    </div>

    <!-- 交易记录表格 -->
    <div class="transaction-table">
      <el-table :data="pagedTransactions" border style="width: 100%">
        <el-table-column prop="id" label="交易编号" width="120"></el-table-column>
        <el-table-column prop="customerName" label="客户姓名" width="120"></el-table-column>
        <el-table-column prop="houseId" label="房屋编号" width="120"></el-table-column>
        <el-table-column prop="houseType" label="房屋类型" width="120"></el-table-column>
        <el-table-column prop="amount" label="预收金额" width="120">
          <template #default="{row}">
            ¥{{ row.amount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已付金额" width="120">
          <template #default="{row}">
            ¥{{ row.paidAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="交易状态" width="120">
          <template #default="{row}">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="截止日期" width="120"></el-table-column>
        <el-table-column prop="lastPaymentDate" label="最后付款日期" width="150"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button size="small" @click="handlePayment(row)">收款</el-button>
            <el-button size="small" type="warning" @click="showDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords">
      </el-pagination>
    </div>

    <!-- 收款对话框 -->
    <el-dialog title="收款记录" v-model="paymentDialogVisible" width="50%">
      <el-form :model="paymentForm" label-width="120px">
        <el-form-item label="交易编号">
          <el-input v-model="currentTransaction.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="currentTransaction.customerName" disabled></el-input>
        </el-form-item>
        <el-form-item label="应收金额">
          <el-input :value="'¥' + currentTransaction.amount.toLocaleString()" disabled></el-input>
        </el-form-item>
        <el-form-item label="已收金额">
          <el-input :value="'¥' + currentTransaction.paidAmount.toLocaleString()" disabled></el-input>
        </el-form-item>
        <el-form-item label="本次收款金额" required>
          <el-input-number
              v-model="paymentForm.amount"
              :min="1"
              :max="currentTransaction.amount - currentTransaction.paidAmount"
              :precision="2"
              controls-position="right"
              style="width: 100%"
              placeholder="请输入本次收款金额">
          </el-input-number>
        </el-form-item>
        <el-form-item label="收款方式" required>
          <el-select v-model="paymentForm.method" placeholder="请选择收款方式" style="width: 100%">
            <el-option label="现金" value="现金"></el-option>
            <el-option label="银行转账" value="银行转账"></el-option>
            <el-option label="支付宝" value="支付宝"></el-option>
            <el-option label="微信支付" value="微信支付"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款备注">
          <el-input type="textarea" v-model="paymentForm.remark" placeholder="请输入收款备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPayment">确认收款</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 交易详情对话框 -->
    <el-dialog title="交易详情" v-model="detailDialogVisible" width="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="交易编号">{{ currentTransaction.id }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentTransaction.customerName }}</el-descriptions-item>
        <el-descriptions-item label="房屋编号">{{ currentTransaction.houseId }}</el-descriptions-item>
        <el-descriptions-item label="房屋类型">{{ currentTransaction.houseType }}</el-descriptions-item>
        <el-descriptions-item label="交易金额">¥{{ currentTransaction.amount.toLocaleString() }}</el-descriptions-item>
        <el-descriptions-item label="已付金额">¥{{ currentTransaction.paidAmount.toLocaleString() }}</el-descriptions-item>
        <el-descriptions-item label="交易状态">
          <el-tag :type="getStatusTagType(currentTransaction.status)">
            {{ currentTransaction.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="截止日期">{{ currentTransaction.dueDate }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentTransaction.createTime }}</el-descriptions-item>
        <el-descriptions-item label="最后付款日期">{{ currentTransaction.lastPaymentDate }}</el-descriptions-item>
      </el-descriptions>

      <h3 style="margin-top: 20px;">付款记录</h3>
      <el-table :data="paymentRecords" border style="width: 100%">
        <el-table-column prop="id" label="付款编号" width="120"></el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{row}">
            ¥{{ row.amount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="method" label="付款方式" width="120"></el-table-column>
        <el-table-column prop="date" label="付款日期" width="150"></el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TransactionManagement',
  data() {
    // 生成模拟交易数据
    const generateTransactions = () => {
      const transactions = [];
      const houseTypes = ['一室一厅', '两室一厅', '三室一厅', '四室两厅', '复式', '别墅'];
      const surnames = ['张', '李', '王', '赵', '刘', '陈', '杨', '黄', '周', '吴'];
      const givenNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军'];

      for (let i = 1; i <= 30; i++) {
        const id = `T2023${String(i).padStart(4, '0')}`;
        const surname = surnames[Math.floor(Math.random() * surnames.length)];
        const givenName = givenNames[Math.floor(Math.random() * givenNames.length)];
        const customerName = `${surname}${givenName}`;
        const houseId = `H${Math.floor(1000 + Math.random() * 9000)}`;
        const houseType = houseTypes[Math.floor(Math.random() * houseTypes.length)];
        const amount = Math.floor(500000 + Math.random() * 3000000);
        const paidAmount = Math.floor(Math.random() * amount * 1.2);
        const status = paidAmount >= amount ? '已交' :
            paidAmount > 0 ? '部分支付' : '未交';

        // 生成日期
        const createDate = new Date();
        createDate.setMonth(createDate.getMonth() - Math.floor(Math.random() * 6));

        const dueDate = new Date(createDate);
        dueDate.setMonth(dueDate.getMonth() + Math.floor(1 + Math.random() * 3));

        let lastPaymentDate = '';
        if (paidAmount > 0) {
          const paymentDate = new Date(createDate);
          paymentDate.setDate(paymentDate.getDate() + Math.floor(Math.random() * 30));
          lastPaymentDate = paymentDate.toLocaleString('zh-CN');
        }

        transactions.push({
          id,
          customerName,
          houseId,
          houseType,
          amount,
          paidAmount: Math.min(paidAmount, amount), // 确保已付不超过总额
          status,
          dueDate: dueDate.toISOString().split('T')[0],
          lastPaymentDate,
          createTime: createDate.toLocaleString('zh-CN')
        });
      }

      return transactions;
    };

    // 生成付款记录
    const generatePaymentRecords = (transactions) => {
      const records = [];
      const methods = ['现金', '银行转账', '支付宝', '微信支付'];
      const operators = ['admin', 'manager', 'finance1', 'finance2'];

      transactions.forEach(transaction => {
        if (transaction.paidAmount > 0) {
          const paymentDate = new Date(transaction.createTime);
          paymentDate.setDate(paymentDate.getDate() + Math.floor(Math.random() * 30));

          // 可能有多笔付款记录
          const paymentCount = Math.max(1, Math.floor(Math.random() * 3));
          let remaining = transaction.paidAmount;

          for (let i = 0; i < paymentCount; i++) {
            const paymentId = `P${new Date().getFullYear()}${String(records.length + 1).padStart(4, '0')}`;
            const amount = i === paymentCount - 1 ? remaining :
                Math.floor(remaining * (0.3 + Math.random() * 0.5));

            records.push({
              id: paymentId,
              transactionId: transaction.id,
              amount,
              method: methods[Math.floor(Math.random() * methods.length)],
              date: paymentDate.toLocaleString('zh-CN'),
              operator: operators[Math.floor(Math.random() * operators.length)],
              remark: `第${i+1}笔付款`
            });

            remaining -= amount;
            paymentDate.setDate(paymentDate.getDate() + Math.floor(Math.random() * 10));
          }
        }
      });

      return records;
    };

    const mockTransactions = generateTransactions();
    const mockPaymentRecords = generatePaymentRecords(mockTransactions);

    // 计算统计信息
    const calculateStats = (transactions) => {
      const total = transactions.length;
      const paid = transactions.filter(t => t.status === '已交').length;
      const paidRate = total > 0 ? Math.round((paid / total) * 100) : 0;
      const totalAmount = transactions.reduce((sum, t) => sum + t.amount, 0);
      const paidAmount = transactions.reduce((sum, t) => sum + t.paidAmount, 0);

      return {
        totalTransactions: total,
        paidRate,
        totalAmount,
        paidAmount
      };
    };

    return {
      searchForm: {
        customerName: '',
        houseId: '',
        status: ''
      },
      transactions: mockTransactions,
      paymentRecords: mockPaymentRecords,
      stats: calculateStats(mockTransactions),
      currentPage: 1,
      pageSize: 10,
      totalRecords: 30,
      paymentDialogVisible: false,
      detailDialogVisible: false,
      currentTransaction: {},
      paymentForm: {
        amount: '',
        method: '',
        remark: ''
      }
    };
  },
  computed: {
    filteredTransactions() {
      let result = this.transactions;
      if (this.searchForm.customerName) {
        result = result.filter(item =>
            item.customerName.includes(this.searchForm.customerName));
      }
      if (this.searchForm.houseId) {
        result = result.filter(item =>
            item.houseId.includes(this.searchForm.houseId));
      }
      if (this.searchForm.status) {
        result = result.filter(item => item.status === this.searchForm.status);
      }
      return result;
    },
    pagedTransactions() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredTransactions.slice(start, end);
    }
  },
  methods: {
    handleSearch() {
      this.currentPage = 1;
      this.stats = this.calculateStats(this.filteredTransactions);
    },
    resetSearch() {
      this.searchForm = {
        customerName: '',
        houseId: '',
        status: ''
      };
      this.currentPage = 1;
      this.stats = this.calculateStats(this.transactions);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handlePayment(row) {
      this.currentTransaction = JSON.parse(JSON.stringify(row));
      this.paymentForm = {
        amount: row.amount - row.paidAmount > 0 ? row.amount - row.paidAmount : '',
        method: '',
        remark: ''
      };
      this.paymentDialogVisible = true;
    },
    submitPayment() {
      const paymentAmount = parseFloat(this.paymentForm.amount);
      if (isNaN(paymentAmount) || paymentAmount <= 0) {
        this.$message.error('请输入有效的收款金额');
        return;
      }

      if (!this.paymentForm.method) {
        this.$message.error('请选择收款方式');
        return;
      }

      // 生成付款记录ID
      const paymentId = 'P' + new Date().getFullYear() +
          String(new Date().getMonth() + 1).padStart(2, '0') +
          String(new Date().getDate()).padStart(2, '0') +
          String(Math.floor(Math.random() * 1000)).padStart(3, '0');

      // 添加付款记录
      const newPayment = {
        id: paymentId,
        transactionId: this.currentTransaction.id,
        amount: paymentAmount,
        method: this.paymentForm.method,
        date: new Date().toLocaleString(),
        operator: 'admin',
        remark: this.paymentForm.remark
      };

      this.paymentRecords.push(newPayment);

      // 更新交易记录
      const index = this.transactions.findIndex(item => item.id === this.currentTransaction.id);
      if (index !== -1) {
        const updatedTransaction = {
          ...this.transactions[index],
          paidAmount: this.transactions[index].paidAmount + paymentAmount,
          lastPaymentDate: new Date().toLocaleString()
        };

        // 更新状态
        if (updatedTransaction.paidAmount >= updatedTransaction.amount) {
          updatedTransaction.status = '已交';
        } else if (updatedTransaction.paidAmount > 0) {
          updatedTransaction.status = '部分支付';
        } else {
          updatedTransaction.status = '未交';
        }

        this.transactions.splice(index, 1, updatedTransaction);
      }

      this.$message.success('收款记录已保存！');
      this.paymentDialogVisible = false;
      this.stats = this.calculateStats(this.transactions);
    },
    showDetail(row) {
      this.currentTransaction = JSON.parse(JSON.stringify(row));
      // 筛选相关付款记录
      this.paymentRecords = this.paymentRecords.filter(
          item => item.transactionId === row.id
      );
      this.detailDialogVisible = true;
    },
    getStatusTagType(status) {
      switch(status) {
        case '已交': return 'success';
        case '未交': return 'danger';
        case '部分支付': return 'warning';
        default: return '';
      }
    },
    getRateColor(rate) {
      if (rate >= 80) return '#67C23A';
      if (rate >= 60) return '#E6A23C';
      return '#F56C6C';
    },
    calculateStats(transactions) {
      const total = transactions.length;
      const paid = transactions.filter(t => t.status === '已交').length;
      const paidRate = total > 0 ? Math.round((paid / total) * 100) : 0;
      const totalAmount = transactions.reduce((sum, t) => sum + t.amount, 0);
      const paidAmount = transactions.reduce((sum, t) => sum + t.paidAmount, 0);

      return {
        totalTransactions: total,
        paidRate,
        totalAmount,
        paidAmount
      };
    }
  }
}
</script>

<style scoped>



.search-bar {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.stats-container {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.stats-cards {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.stat-card {
  flex: 1;
  margin: 0 10px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.transaction-table {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  background: #ffffff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 对话框样式 */
.el-dialog {
  background-color: rgba(255, 255, 255, 0.95);
}
</style>